################################################################################
#  EG4 project, Anyang Normal University && IMP-CAS
#  \brief cmake macros specifically used in EG4
#  \author SUN Yazhou, asia.rabbit@163.com
#  \since 2023-11-21
#  \date 2023-11-21
#  \attention
#  changelog
#  <table>
#  <tr>  <th>Date         <th>Author      <th>Description                  </tr>
#  <tr>  <td>2023-11-21   <td>Asia Sun    <td>file created                 </tr>
#  </table>
#  \copyright Copyright (c) 2021-2023 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
################################################################################

function(eg4_rootGen target)
  cmake_parse_arguments(PARSE_ARGV 1 "A" "" "LINKDEF" "HEADERS")
  # check argument validity
  if(A_UNPARSED_ARGUMENTS)
    message(FATAL_ERROR "Unexpected unparsed arguments: ${A_UNPARESD_ARGUMENTS}")
  endif()
  set(required_args "LINKDEF;HEADERS")
  foreach(r IN LISTS required_args)
    if(NOT A_${r})
      message(FATAL_ERROR "Missing required argument: ${r}")
    endif()
  endforeach()

  # input headers are all of absolute paths, while linkfile is not
  unset(headers)
  list(APPEND headers ${A_HEADERS} ${CMAKE_CURRENT_SOURCE_DIR}/${A_LINKDEF})

  set(dict G__${target})
  set(dictFile ${CMAKE_CURRENT_BINARY_DIR}/${dict}.cxx)
  set(pcmBase ${dict}_rdict.pcm)
  set(pcmFile ${LIBRARY_OUTPUT_PATH}/${pcmBase})
  set(rmFile ${LIBRARY_OUTPUT_PATH}/lib${target}.rootmap)

  # get target properties #
  set(incdirs $<TARGET_PROPERTY:${target},INCLUDE_DIRECTORIES>)
  set(incdirs "$<REMOVE_DUPLICATES:${incdirs}>")

  add_custom_command(
    OUTPUT ${dictFile} ${pcmFile} ${rmFile}
    VERBATIM
    COMMAND $<TARGET_FILE:ROOT::rootcling>
      -f ${dictFile} -rmf ${rmFile}
      -rml $<TARGET_FILE_NAME:${target}>
      -I$<JOIN:${incdirs},$<SEMICOLON>-I>
      -c ${headers}
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
      ${CMAKE_CURRENT_BINARY_DIR}/${pcmBase} ${pcmFile}
    COMMAND_EXPAND_LISTS
    DEPENDS ${headers}
  )
  target_sources(${target} PRIVATE ${dictFile})
endfunction()

function(eg4_change_ext sfx0 sfx1)
  cmake_parse_arguments(A "" "OUTVAR" "FILES" ${ARGN})
  if(A_UNPARSED_ARGUMENTS)
    message(FATAL_ERROR "Unexpected unparsed arguments: ${A_UNPARESD_ARGUMENTS}")
  endif()

  set(required_args "FILES")
  foreach(r IN LISTS required_args)
    if(NOT A_${r})
      message(FATAL_ERROR "Missing required argument: ${r}")
    endif()
  endforeach()

  foreach(f ${A_FILES})
    set(new "")
    string(REGEX REPLACE "^(.*)${sfx0}$" "\\1${sfx1}" new ${f})
    if(NOT ${f} STREQUAL ${new} AND EXISTS ${new})
      list(APPEND result ${new})
    endif()
  endforeach()
  set(${A_OUTVAR} ${result} PARENT_SCOPE)
endfunction()
